<?php

// 发立得信息发布系统房屋信息版(php+mysql) V1.0
// 演示地址: http://fang.chalide.cn
// 文件路径: install.php
// 文件大小: 21066 字节
// 最后修改时间: 2025-06-09 18:51:56
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权
/**
 * 本文件功能：数据库安装
 * 版权声明：保留发行权和署名权
 * 作者信息：15058593138@qq.com
 */

// 引入数据库配置
require_once './inc/conn.php';

// 处理AJAX请求
if (isset($_GET['act'])) {
    header('Content-Type: application/json; charset=utf-8');
    
    $act = $_GET['act'];
    
    switch ($act) {
        // 检查环境
        case 'check':
            $result = [
                'code' => 1,
                'msg' => '检查完成',
                'data' => [
                    'php_version' => PHP_VERSION,
                    'php_version_ok' => version_compare(PHP_VERSION, '7.1.0', '>='),
                    'mysql_ok' => extension_loaded('mysqli'),
                    'gd_ok' => extension_loaded('gd'),
                    'writeable' => checkDirWriteable()
                ]
            ];
            
            echo json_encode($result, JSON_UNESCAPED_UNICODE);
            break;
            
        // 安装数据库
        case 'install':
            // 检查是否导入演示数据
            $demo = isset($_POST['demo']) ? $_POST['demo'] : 0;
            
            // 尝试连接数据库
            try {
                $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, '', DB_PORT);
                
                if ($conn->connect_error) {
                    echo json_encode([
                        'code' => 0,
                        'msg' => '数据库连接失败: ' . $conn->connect_error
                    ], JSON_UNESCAPED_UNICODE);
                    break;
                }
                
                // 设置字符集
                $conn->set_charset(DB_CHARSET);
                
                // 创建数据库
                $create_db_sql = "CREATE DATABASE IF NOT EXISTS `" . DB_NAME . "` DEFAULT CHARACTER SET " . DB_CHARSET;
                if (!$conn->query($create_db_sql)) {
                    echo json_encode([
                        'code' => 0,
                        'msg' => '创建数据库失败: ' . $conn->error
                    ], JSON_UNESCAPED_UNICODE);
                    break;
                }
                
                // 选择数据库
                $conn->select_db(DB_NAME);
                
                // 执行安装SQL
                $install_sql = file_get_contents('./install.sql');
                $sqls = explode(';', $install_sql);
                
                $tables = [];
                
                foreach ($sqls as $sql) {
                    $sql = trim($sql);
                    if (empty($sql)) continue;
                    
                    if ($conn->query($sql)) {
                        // 提取表名
                        if (preg_match('/CREATE TABLE.*?`(.*?)`/i', $sql, $matches)) {
                            $tables[] = [
                                'name' => $matches[1],
                                'status' => 1
                            ];
                        }
                    } else {
                        // 提取表名
                        if (preg_match('/CREATE TABLE.*?`(.*?)`/i', $sql, $matches)) {
                            $tables[] = [
                                'name' => $matches[1],
                                'status' => 0,
                                'error' => $conn->error
                            ];
                        }
                    }
                }
                
                // 添加默认管理员账号
                $admin_pass = md5('admin123');
                $add_admin_sql = "INSERT INTO `user` (`user`, `pass`, `type`, `mobi`, `add_time`, `log_time`, `status`) 
                                 VALUES ('15058593138@qq.com', '$admin_pass', 8, '13800138000', NOW(), NULL, 1)";
                
                $conn->query($add_admin_sql);
                
                // 导入演示数据
                $demo_result = [];
                if ($demo == 1) {
                    $demo_sql = file_get_contents('./demo.sql');
                    $demo_sqls = explode(';', $demo_sql);
                    
                    foreach ($demo_sqls as $sql) {
                        $sql = trim($sql);
                        if (empty($sql)) continue;
                        
                        if ($conn->query($sql)) {
                            // 提取表名
                            if (preg_match('/INSERT INTO.*?`(.*?)`/i', $sql, $matches)) {
                                $table = $matches[1];
                                if (!isset($demo_result[$table])) {
                                    $demo_result[$table] = [
                                        'name' => $table,
                                        'success' => 1,
                                        'error' => 0
                                    ];
                                } else {
                                    $demo_result[$table]['success']++;
                                }
                            }
                        } else {
                            // 提取表名
                            if (preg_match('/INSERT INTO.*?`(.*?)`/i', $sql, $matches)) {
                                $table = $matches[1];
                                if (!isset($demo_result[$table])) {
                                    $demo_result[$table] = [
                                        'name' => $table,
                                        'success' => 0,
                                        'error' => 1
                                    ];
                                } else {
                                    $demo_result[$table]['error']++;
                                }
                            }
                        }
                    }
                }
                
                // 创建站点配置文件
                $site_config = json_encode($CONFIG, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
                file_put_contents('./inc/site.json', $site_config);
                
                echo json_encode([
                    'code' => 1,
                    'msg' => '安装成功',
                    'data' => [
                        'tables' => $tables,
                        'demo' => $demo_result
                    ]
                ], JSON_UNESCAPED_UNICODE);
                
            } catch (Exception $e) {
                echo json_encode([
                    'code' => 0,
                    'msg' => '安装失败: ' . $e->getMessage()
                ], JSON_UNESCAPED_UNICODE);
            }
            break;
            
        default:
            echo json_encode([
                'code' => 0,
                'msg' => '未知操作'
            ], JSON_UNESCAPED_UNICODE);
    }
    
    exit;
}

/**
 * 检查目录是否可写
 * @return array 检查结果
 */
function checkDirWriteable() {
    $dirs = [
        './',
        './inc',
        './imgs'
    ];
    
    $result = [];
    
    foreach ($dirs as $dir) {
        $result[$dir] = is_writable($dir);
    }
    
    return $result;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>房屋信息发布平台 - 安装</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            font-size: 14px;
            line-height: 1.5;
            color: #333;
            background-color: #f5f5f5;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: #fff;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            padding: 20px;
        }
        
        h1 {
            text-align: center;
            margin-bottom: 20px;
            color: #0066cc;
        }
        
        .step {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .step-title {
            margin-bottom: 10px;
            font-size: 18px;
            font-weight: bold;
        }
        
        .step-body {
            margin-bottom: 10px;
        }
        
        .step-footer {
            text-align: right;
        }
        
        .btn {
            display: inline-block;
            padding: 6px 12px;
            background: #0066cc;
            color: #fff;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        
        .btn:hover {
            background: #0059b3;
        }
        
        .table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 15px;
        }
        
        .table th, .table td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: left;
        }
        
        .table th {
            background: #f5f5f5;
        }
        
        .success {
            color: green;
        }
        
        .error {
            color: red;
        }
        
        .checkbox-group {
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>房屋信息发布平台安装向导</h1>
        
        <div class="step" id="step1">
            <div class="step-title">第一步：环境检查</div>
            <div class="step-body" id="check-result">
                <p>正在检查环境...</p>
            </div>
            <div class="step-footer">
                <button type="button" class="btn" id="check-btn">检查环境</button>
                <button type="button" class="btn" id="next-btn" style="display:none;">下一步</button>
            </div>
        </div>
        
        <div class="step" id="step2" style="display:none;">
            <div class="step-title">第二步：数据库安装</div>
            <div class="step-body">
                <p>数据库配置信息：</p>
                <table class="table">
                    <tr>
                        <th width="30%">数据库主机</th>
                        <td><?php echo DB_HOST; ?></td>
                    </tr>
                    <tr>
                        <th>数据库端口</th>
                        <td><?php echo DB_PORT; ?></td>
                    </tr>
                    <tr>
                        <th>数据库用户名</th>
                        <td><?php echo DB_USER; ?></td>
                    </tr>
                    <tr>
                        <th>数据库密码</th>
                        <td>******</td>
                    </tr>
                    <tr>
                        <th>数据库名</th>
                        <td><?php echo DB_NAME; ?></td>
                    </tr>
                    <tr>
                        <th>数据库编码</th>
                        <td><?php echo DB_CHARSET; ?></td>
                    </tr>
                </table>
                
                <div class="checkbox-group">
                    <label>
                        <input type="checkbox" id="demo-data"> 导入演示数据（30+条用于分页演示）
                    </label>
                </div>
                
                <div id="install-result"></div>
            </div>
            <div class="step-footer">
                <button type="button" class="btn" id="prev-btn">上一步</button>
                <button type="button" class="btn" id="install-btn">开始安装</button>
            </div>
        </div>
        
        <div class="step" id="step3" style="display:none;">
            <div class="step-title">第三步：安装完成</div>
            <div class="step-body">
                <p>恭喜您，房屋信息发布平台安装成功！</p>
                <p>默认管理员账号：15058593138@qq.com</p>
                <p>默认管理员密码：admin123</p>
                <p class="error">为了安全，请安装完成后立即修改默认密码！</p>
            </div>
            <div class="step-footer">
                <a href="index.php" class="btn">前台首页</a>
                <a href="sys.php" class="btn">管理后台</a>
            </div>
        </div>
    </div>
    
    <script>
        // 检查环境按钮
        document.getElementById('check-btn').addEventListener('click', function() {
            checkEnvironment();
        });
        
        // 下一步按钮
        document.getElementById('next-btn').addEventListener('click', function() {
            document.getElementById('step1').style.display = 'none';
            document.getElementById('step2').style.display = 'block';
        });
        
        // 上一步按钮
        document.getElementById('prev-btn').addEventListener('click', function() {
            document.getElementById('step2').style.display = 'none';
            document.getElementById('step1').style.display = 'block';
        });
        
        // 安装按钮
        document.getElementById('install-btn').addEventListener('click', function() {
            installDatabase();
        });
        
        // 检查环境
        function checkEnvironment() {
            const checkResult = document.getElementById('check-result');
            checkResult.innerHTML = '<p>正在检查环境...</p>';
            
            // 发送AJAX请求
            const xhr = new XMLHttpRequest();
            xhr.open('GET', 'install.php?act=check', true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        try {
                            const res = JSON.parse(xhr.responseText);
                            if (res.code === 1) {
                                renderCheckResult(res.data);
                            } else {
                                checkResult.innerHTML = '<p class="error">' + res.msg + '</p>';
                            }
                        } catch (e) {
                            checkResult.innerHTML = '<p class="error">解析响应失败</p>';
                        }
                    } else {
                        checkResult.innerHTML = '<p class="error">请求失败</p>';
                    }
                }
            };
            xhr.send();
        }
        
        // 渲染检查结果
        function renderCheckResult(data) {
            const checkResult = document.getElementById('check-result');
            let html = '<table class="table">';
            
            // PHP版本
            html += '<tr>';
            html += '<th>PHP版本</th>';
            html += '<td>' + data.php_version + '</td>';
            html += '<td>' + (data.php_version_ok ? '<span class="success">通过</span>' : '<span class="error">不通过</span>') + '</td>';
            html += '</tr>';
            
            // MySQL扩展
            html += '<tr>';
            html += '<th>MySQL扩展</th>';
            html += '<td>mysqli</td>';
            html += '<td>' + (data.mysql_ok ? '<span class="success">通过</span>' : '<span class="error">不通过</span>') + '</td>';
            html += '</tr>';
            
            // GD扩展
            html += '<tr>';
            html += '<th>GD扩展</th>';
            html += '<td>gd</td>';
            html += '<td>' + (data.gd_ok ? '<span class="success">通过</span>' : '<span class="error">不通过</span>') + '</td>';
            html += '</tr>';
            
            // 目录权限
            html += '<tr>';
            html += '<th rowspan="' + Object.keys(data.writeable).length + '">目录权限</th>';
            
            let i = 0;
            for (let dir in data.writeable) {
                if (i > 0) html += '<tr>';
                html += '<td>' + dir + '</td>';
                html += '<td>' + (data.writeable[dir] ? '<span class="success">可写</span>' : '<span class="error">不可写</span>') + '</td>';
                if (i > 0) html += '</tr>';
                i++;
            }
            
            html += '</table>';
            
            // 检查是否全部通过
            const allPassed = data.php_version_ok && data.mysql_ok && data.gd_ok && 
                              Object.values(data.writeable).every(item => item === true);
            
            if (allPassed) {
                html += '<p class="success">恭喜，您的环境已满足安装要求！</p>';
                document.getElementById('next-btn').style.display = 'inline-block';
            } else {
                html += '<p class="error">抱歉，您的环境不满足安装要求，请检查后重试！</p>';
                document.getElementById('next-btn').style.display = 'none';
            }
            
            checkResult.innerHTML = html;
        }
        
        // 安装数据库
        function installDatabase() {
            const installResult = document.getElementById('install-result');
            const installBtn = document.getElementById('install-btn');
            
            installResult.innerHTML = '<p>正在安装数据库...</p>';
            installBtn.disabled = true;
            
            // 获取是否导入演示数据
            const demoData = document.getElementById('demo-data').checked ? 1 : 0;
            
            // 发送AJAX请求
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'install.php?act=install', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        try {
                            const res = JSON.parse(xhr.responseText);
                            if (res.code === 1) {
                                renderInstallResult(res.data);
                                // 显示第三步
                                document.getElementById('step2').style.display = 'none';
                                document.getElementById('step3').style.display = 'block';
                            } else {
                                installResult.innerHTML = '<p class="error">' + res.msg + '</p>';
                                installBtn.disabled = false;
                            }
                        } catch (e) {
                            installResult.innerHTML = '<p class="error">解析响应失败</p>';
                            installBtn.disabled = false;
                        }
                    } else {
                        installResult.innerHTML = '<p class="error">请求失败</p>';
                        installBtn.disabled = false;
                    }
                }
            };
            xhr.send('demo=' + demoData);
        }
        
        // 渲染安装结果
        function renderInstallResult(data) {
            const installResult = document.getElementById('install-result');
            let html = '<p class="success">数据库安装成功！</p>';
            
            // 表创建结果
            html += '<h3>数据表创建结果：</h3>';
            html += '<table class="table">';
            html += '<tr><th>表名</th><th>状态</th></tr>';
            
            for (let i = 0; i < data.tables.length; i++) {
                const table = data.tables[i];
                html += '<tr>';
                html += '<td>' + table.name + '</td>';
                html += '<td>' + (table.status === 1 ? '<span class="success">成功</span>' : '<span class="error">失败：' + table.error + '</span>') + '</td>';
                html += '</tr>';
            }
            
            html += '</table>';
            
            // 演示数据导入结果
            if (data.demo && Object.keys(data.demo).length > 0) {
                html += '<h3>演示数据导入结果：</h3>';
                html += '<table class="table">';
                html += '<tr><th>表名</th><th>成功</th><th>失败</th></tr>';
                
                for (let table in data.demo) {
                    const item = data.demo[table];
                    html += '<tr>';
                    html += '<td>' + item.name + '</td>';
                    html += '<td>' + item.success + '</td>';
                    html += '<td>' + item.error + '</td>';
                    html += '</tr>';
                }
                
                html += '</table>';
            }
            
            installResult.innerHTML = html;
        }
        
        // 页面加载完成后自动检查环境
        window.onload = function() {
            checkEnvironment();
        };
    </script>
</body>
</html>